package com.ruoyi.ex.service.impl;

import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.doudou.core.thread.ExecutorUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.aliyun.MySms;
import com.ruoyi.common.value.Values;
import com.ruoyi.pv.domain.PvStudentRecord;
import com.ruoyi.pv.service.IPvStudentRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ex.mapper.ExQuestionBankMapper;
import com.ruoyi.ex.domain.ExQuestionBank;
import com.ruoyi.ex.service.IExQuestionBankService;

/**
 * 题库Service业务层处理
 *
 * @author zzx
 * @date 2023-03-23
 */
@Service
@Slf4j
public class ExQuestionBankServiceImpl implements IExQuestionBankService {

    @Autowired private ExQuestionBankMapper exQuestionBankMapper;
    @Autowired private RedisCache redisCache;
    @Autowired private IPvStudentRecordService studentRecordService;
//    @Autowired private MySms sms;

    /**
     * 查询题库
     *
     * @param id 题库主键
     * @return 题库
     */
    @Override
    public ExQuestionBank selectExQuestionBankById(Long id) {
        return exQuestionBankMapper.selectExQuestionBankById(id);
    }

    /**
     * 查询题库列表
     *
     * @param exQuestionBank 题库
     * @return 题库
     */
    @Override
    public List<ExQuestionBank> selectExQuestionBankList(ExQuestionBank exQuestionBank) {
        return exQuestionBankMapper.selectExQuestionBankList(exQuestionBank);
    }

    /**
     * 新增题库
     *
     * @param exQuestionBank 题库
     * @return 结果
     */
    @Override
    public int insertExQuestionBank(ExQuestionBank exQuestionBank) {
                exQuestionBank.setCreateTime(DateUtils.getNowDate());
            return exQuestionBankMapper.insertExQuestionBank(exQuestionBank);
    }

    /**
     * 修改题库
     *
     * @param exQuestionBank 题库
     * @return 结果
     */
    @Override
    public int updateExQuestionBank(ExQuestionBank exQuestionBank) {
        return exQuestionBankMapper.updateExQuestionBank(exQuestionBank);
    }

    /**
     * 批量删除题库
     *
     * @param ids 需要删除的题库主键
     * @return 结果
     */
    @Override
    public int deleteExQuestionBankByIds(Long[] ids) {
        return exQuestionBankMapper.deleteExQuestionBankByIds(ids);
    }

    /**
     * 删除题库信息
     *
     * @param id 题库主键
     * @return 结果
     */
    @Override
    public int deleteExQuestionBankById(Long id) {
        return exQuestionBankMapper.deleteExQuestionBankById(id);
    }

    @Override
    public int selectExQuestionBankCountById(Long bankId) {
        return exQuestionBankMapper.selectExQuestionBankCountById(bankId);
    }

    @Override
    public List<ExQuestionBank> selectExQuestionExList(ExQuestionBank exQuestionBank) {
        return exQuestionBankMapper.selectExQuestionExList(exQuestionBank);
    }

    @Override
    public void saveAnswers(Long userId, Long bankId, JSONObject answers) {
        //组装key
        String key = StrUtil.format(Values.EX_DOING_ANSWER_KEY,new HashMap<String,Object>(){{
            put("userId",userId);put("bandId",bankId);
        }});
        redisCache.setCacheObject(key,answers,1, TimeUnit.DAYS);
    }

    @Override
    public JSONObject getAnswers(Long userId,Long bankId) {
        //组装key
        String key = StrUtil.format(Values.EX_DOING_ANSWER_KEY,new HashMap<String,Object>(){{
            put("userId",userId);put("bandId",bankId);
        }});
        Object cacheObject = redisCache.getCacheObject(key);
        return ObjectUtil.isNotEmpty(cacheObject) ? JSONUtil.parseObj(cacheObject) : JSONUtil.createObj();
    }

    @Override
    public void smsSend(Long id, List<Long> classIds, Integer trainFlag) {
        //查询题库详情
        ExQuestionBank bank = exQuestionBankMapper.selectExQuestionBankById(id);
        //查询用户
        Set<SysUser> users = getUsers(classIds,trainFlag);
        //创建线程池
        ThreadPoolExecutor executor = ExecutorUtil.customThreadExecutor(4, 4, 0L, users.size());
        //发送短信
//        for (SysUser user : users) {
//            executor.execute(()->{
//                if (StrUtil.isNotBlank(user.getPostsNumber())){
//                    sms.sendFirstEx(user.getPhonenumber(),user.getNickName(),
//                            DateUtil.thisYear(),
//                            DateUtil.formatDate(bank.getReservedOneList().getDate(0)),
//                            DateUtil.formatDate(bank.getReservedOneList().getDate(1)),
//                            bank.getReservedTwoList().getJSONObject(0).getJSONArray("time").getStr(0));
//                }
//            });
//        }
    }

    @Override
    public int smsSendPeopleCount(List<Long> classIds, Integer trainFlag) {
        return getUsers(classIds,trainFlag).size();
    }

    private Set<SysUser> getUsers(List<Long> classIds, Integer trainFlag){
        //查询用户
        Set<SysUser> users = new HashSet<>();
        List<PvStudentRecord> pvStudentRecords;
        //查询用户
        for (Long classId : classIds) {
            SysUser sysUser = new SysUser();
            if (trainFlag != 2){//初复训
                sysUser.setParams(new HashMap<String,Object>(){{put("initial",trainFlag.toString());}});
            }
            pvStudentRecords = studentRecordService.selectPvTrainingClassStudentList(classId,sysUser);
            users.addAll(parseUsers(pvStudentRecords));
        }
        return users;
    }

    private Set<SysUser> parseUsers(List<PvStudentRecord> pvStudentRecords){
        return pvStudentRecords.stream().map(PvStudentRecord::getStudent).collect(Collectors.toSet());
    }
}
